package marmalius.tools;

import java.io.PrintStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class LogService {
	private static final LogService instance = new LogService();
	private int logLevel;
	private PrintStream fOut;
	private Date date;
	private SimpleDateFormat dateFormat;
	
	public LogService () {
		fOut = null;
		date = null;
	}
	
	public boolean init(int logLevel, String logFile, boolean logTime) {
		this.logLevel = logLevel;
		if (logTime) {
			date = new Date();
			dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		}
		if (!logFile.isEmpty()) {
			try {
				fOut = new PrintStream(new FileOutputStream("log.txt", true));
			}
			catch (FileNotFoundException ex) {
				System.out.println(ex);
				return false;
			}
		}
		return true;
	}
	
	public void logError(String message) {
		if ((logLevel & 1) == 1)
			addLog("[ERROR]"+message);
	}
	
	public void logWarn(String message) {
		if ((logLevel & 2) == 2)
			addLog("[WARN]"+message);
	}
	
	public void logInfo(String message) {
		if ((logLevel & 4) == 4)
			addLog("[INFO]"+message);
	}
	
	public void logDebug(String message) {
		if ((logLevel & 8) == 8)
			addLog("[DEBUG]"+message);
	}
	
	public void logCommand(String message) {
		if ((logLevel & 16) == 16)
			addLog("[COMMAND]"+message);
	}
	
	public void logChat(String message) {
		if ((logLevel & 32) == 32)
			addLog("[CHAT]"+message);
	}
	
	public void close () {
		if (fOut != null)
		fOut.close();
	}
	
	private void addLog(String message) {
		if (date != null)
			message = dateFormat.format(date) + message;
		System.out.println(message);
		if (fOut != null)
			fOut.println(message);
	}
	
	public static LogService getInstance() { return instance; }
}